from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import List

from common.database import get_db
from common.welab_k8s import init_k8s
from core.response import resp_200, resp_400
from core.logger import logger

# from app.service_quality.handlers.qos_host_info_handler import QosHostInfoHandler
# from app.service_quality.handlers.qos_host_disk_handler import QosHostDiskHandler
# from app.service_quality.handlers.qos_host_date_handler import QosHostDateHandler
from app.service_quality.handlers.qos_server_info_handler import QosServerInfoHandler
from app.service_quality.handlers.qos_server_date_handler import QosServerDateHandler
from app.service_quality.handlers.qos_paint_diagram_handler import QosPaintDiagramHandler
from app.service_quality.handlers.qos_http_chart_handler import http_reg_time_ratio_chart_handler
from app.service_quality.handlers.qos_http_chart_handler import http_4xx_chart_handler
from app.service_quality.handlers.qos_http_chart_handler import http_5xx_chart_handler
from core.security import permission_checker

from app.service_quality.models.qos_process_io import QosProcessIo

from app.service_quality.schemas import *


router = APIRouter()


# #### 服务器信息操作 ####
# @router.get('/host/info/', summary="获取主机信息, 根据表字段--模糊匹配", description="服务质量-基础物理机")
# async def get_qos_host_info_search(quality_date: str = Query(..., description="日期"), field: str = Query("all"),
#                                value: str = Query(""), page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
#                                db: Session = Depends(get_db), user=Depends(permission_checker)):
#     qos_host_info_handler = QosHostInfoHandler()
#     status, result = qos_host_info_handler.get_host_info_search(db, quality_date, page, per_page, field, value)
#     if not status:
#         message = "get host info search failed"
#         logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
#         return resp_400(message)
#     return resp_200(result)


# @router.get('/host/info/match/', summary="获取主机信息, 根据表字段--完全匹配", description="服务质量-基础物理机")
# async def get_qos_host_info_match(quality_date: str = Query(..., description="日期"),
#                               field: str = Query(..., description="需要查询的字段"),
#                               value: str = Query(..., description="字段的值"),
#                               page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
#                               db: Session = Depends(get_db), user=Depends(permission_checker)):
#     qos_host_info_handler = QosHostInfoHandler()
#     status, result = qos_host_info_handler.get_host_info_match(db, quality_date, page, per_page, field, value)
#     if not status:
#         message = "get host info match failed"
#         logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
#         return resp_400(message)
#     return resp_200(result)


# @router.get('/host/info/k8s_node/', summary="获取k8s集群node节点主机信息", description="服务质量-基础物理机")
# async def get_qos_host_info_k8s_node(k8s: None = Depends(init_k8s), user=Depends(permission_checker)):
#     qos_host_info_handler = QosHostInfoHandler()
#     result = qos_host_info_handler.get_host_info_k8s_node()
#     if not result:
#         message = "get host info k8s node failed"
#         logger.error(message)
#         return resp_400(message)
#     return resp_200(result)



# @router.post('/host/info/task/', summary="启动录入主机信息的异步任务", description="服务质量-基础物理机")
# async def post_qos_host_info_task(db: Session = Depends(get_db), user=Depends(permission_checker)):
#     qos_host_info_handler = QosHostInfoHandler()
#     result = qos_host_info_handler.post_host_info_task(db)
#     if not result:
#         message = "post host info task failed"
#         logger.error(message)
#         return resp_400(message)
#     return resp_200(result)





# #### 服务器磁盘操作 ####
# @router.get('/host/disk/', summary="获取磁盘信息, 根据表字段--模糊匹配", description="服务质量-基础物理机")
# async def get_qos_host_disk_search(quality_date: str = Query(..., description="日期"), field: str = Query("all"),
#                                value: str = Query(""), page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
#                                db: Session = Depends(get_db), user=Depends(permission_checker)):
#     qos_host_disk_handler = QosHostDiskHandler()
#     status, result = qos_host_disk_handler.get_host_disk_search(db, quality_date, page, per_page, field, value)
#     if not status:
#         message = "get host disk search failed"
#         logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
#         return resp_400(message)
#     return resp_200(result)


# @router.get('/host/disk/match/', summary="获取磁盘信息, 根据表字段--完全匹配", description="服务质量-基础物理机")
# async def get_qos_host_disk_match(quality_date: str = Query(..., description="日期"),
#                               field: str = Query(..., description="需要查询的字段"),
#                               value: str = Query(..., description="字段的值"),
#                               page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
#                               db: Session = Depends(get_db), user=Depends(permission_checker)):
#     qos_host_disk_handler = QosHostDiskHandler()
#     status, result = qos_host_disk_handler.get_host_disk_match(db, quality_date, page, per_page, field, value)
#     if not status:
#         message = "get host disk match failed"
#         logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
#         return resp_400(message)
#     return resp_200(result)



# @router.post('/host/disk/task/', summary="启动录入磁盘信息的异步任务", description="服务质量-基础物理机")
# async def post_qos_host_disk_task(db: Session = Depends(get_db), user=Depends(permission_checker)):
#     qos_host_disk_handler = QosHostDiskHandler()
#     result = qos_host_disk_handler.post_host_disk_task(db)
#     if not result:
#         message = "post host disk task failed"
#         logger.error(message)
#         return resp_400(message)
#     return resp_200(result)









# #### 服务器质量操作 ####
# @router.get('/host/date/', summary="获取主机监控信息, 根据表字段--模糊匹配", description="服务质量-基础物理机")
# async def get_qos_host_date_search(quality_date: str = Query(..., description="日期"), field: str = Query("all"),
#                                value: str = Query(""), page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
#                                db: Session = Depends(get_db), user=Depends(permission_checker)):
#     qos_host_date_handler = QosHostDateHandler()
#     status, result = qos_host_date_handler.get_host_date_search(db, quality_date, page, per_page, field, value)
#     if not status:
#         message = "get host date search failed"
#         logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
#         return resp_400(message)
#     return resp_200(result)


# @router.get('/host/date/match/', summary="获取主机监控信息, 根据表字段--完全匹配", description="服务质量-基础物理机")
# async def get_qos_host_date_match(quality_date: str = Query(..., description="日期"),
#                               field: str = Query(..., description="需要查询的字段"),
#                               value: str = Query(..., description="字段的值"),
#                               page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
#                               db: Session = Depends(get_db), user=Depends(permission_checker)):
#     qos_host_date_handler = QosHostDateHandler()
#     status, result = qos_host_date_handler.get_host_date_match(db, quality_date, page, per_page, field, value)
#     if not status:
#         message = "get host date match failed"
#         logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
#         return resp_400(message)
#     return resp_200(result)


# @router.post('/host/date/task/', summary="启动同步主机监控数据的异步任务", description="服务质量-基础物理机")
# async def post_qos_host_date_task(data: PostHostDateTask, db: Session = Depends(get_db), user=Depends(permission_checker)):
#     qos_host_date_handler = QosHostDateHandler()
#     data = {"quality_date": data.quality_date.strftime("%Y-%m-%d")}
#     result = qos_host_date_handler.post_host_date_task(db, data)
#     if not result:
#         message = "post host date task failed"
#         logger.error(f"{message} => data:{data}")
#         return resp_400(message)
#     return resp_200(result)








#### 应用服务信息操作 ####
@router.get('/server/info/', summary="获取应用服务信息, 根据表字段-模糊匹配", description="服务质量-应用服务")
async def get_qos_server_info_search(field: str = Query("all"), value: str = Query(""), page: int = Query(1, ge=1),
                                 per_page: int = Query(10, ge=0),
                                 db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_info_handler = QosServerInfoHandler()
    status, result = qos_server_info_handler.get_server_info_search(db, page, per_page, field, value)
    if not status:
        message = "get server info search failed"
        logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
        return resp_400(message)
    return resp_200(result)


@router.get('/server/info/match/', summary="获取应用服务信息, 根据表字段-完全匹配", description="服务质量-应用服务")
async def get_qos_server_info_match(field: str = Query(..., description="需要查询的字段"),
                                value: str = Query(..., description="字段的值"),
                                page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
                                db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_info_handler = QosServerInfoHandler()
    result = qos_server_info_handler.get_server_info_match(db, page, per_page, field, value)
    if not result:
        message = "get server info match failed"
        logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
        return resp_400(message)
    return resp_200(result)


@router.get('/server/info/count/', summary="获取应用服务根据classes聚合统计的数量信息", description="服务质量-应用服务")
async def get_qos_server_info_count(db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_info_handler = QosServerInfoHandler()
    result = qos_server_info_handler.get_server_info_count(db)
    if not result:
        message = "get server info count failed"
        logger.error(f"{message}")
        return resp_400(message)
    return resp_200(result)


@router.post('/server/info/', summary="增加应用服务信息", description="服务质量-应用服务")
async def post_qos_server_info(data: PostServerInfo, db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_info_handler = QosServerInfoHandler()
    result = qos_server_info_handler.add_server_info(db, data.dict())
    if not result:
        message = "post server info failed"
        logger.error(f"{message} => data:{data.dict()}")
        return resp_400(message)
    return resp_200()


@router.put('/server/info/', summary="修改告应用服务信息", description="服务质量-应用服务")
async def put_qos_server_info(data: PutServerInfo, db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_info_handler = QosServerInfoHandler()
    result = qos_server_info_handler.update_server_info(db, data.dict())
    if not result:
        message = "put server info failed"
        logger.error(f"{message} => data:{data.dict()}")
        return resp_400(message)
    return resp_200()


@router.delete('/server/info/', summary="删除应用服务信息", description="服务质量-应用服务")
async def delete_qos_server_info(data: DelBaseModel, db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_info_handler = QosServerInfoHandler()
    result = qos_server_info_handler.delete_server_info(db, data.dict())
    if not result:
        message = "delete server info failed"
        logger.error(f"{message} => data:{data.dict()}")
        return resp_400(message)
    return resp_200()


@router.post('/server/info/task/', summary="启动同步容器服务信息到数据库的异步任务", description="服务质量-应用服务")
async def post_qos_server_info_task(db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_info_handler = QosServerInfoHandler()
    result = qos_server_info_handler.post_server_info_task(db)
    if not result:
        message = "post server info task failed"
        logger.error(f"{message}")
        return resp_400(message)
    return resp_200(result)








#### 应用服务质量操作 ####
@router.get('/server/date/', summary="获取应用服务监控信息, 根据表字段--模糊匹配", description="服务质量-应用服务")
async def get_qos_server_date_search(quality_date: str = Query(..., description="日期"), field: str = Query("all"),
                                 value: str = Query(""), page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
                                 db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_date_handler = QosServerDateHandler()
    status, result = qos_server_date_handler.get_server_date_search(db, quality_date, page, per_page, field, value)
    if not status:
        message = "get server date search failed"
        logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
        return resp_400(message)
    return resp_200(result)


@router.get('/server/date/match/', summary="获取应用服务监控信息, 根据表字段--完全匹配", description="服务质量-应用服务")
async def get_qos_server_date_match(quality_date: str = Query(..., description="日期"),
                                field: str = Query(..., description="需要查询的字段"),
                                value: str = Query(..., description="字段的值"),
                                page: int = Query(1, ge=1), per_page: int = Query(10, ge=0),
                                db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_date_handler = QosServerDateHandler()
    status, result = qos_server_date_handler.get_server_date_match(db, quality_date, page, per_page, field, value)
    if not status:
        message = "get server date match failed"
        logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
        return resp_400(message)
    return resp_200(result)



@router.get('/server/date/week/', summary="获取一个服务最近7天的监控信息", description="服务质量-应用服务")
async def get_qos_server_date_week(server_name: str = Query(..., description="服务名称"),
                                db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_date_handler = QosServerDateHandler()
    status, result = qos_server_date_handler.get_server_date_week(db, server_name)
    if not status:
        message = "get server date week failed"
        logger.error(f"{message} => server_name:{server_name}")
        return resp_400(message)
    return resp_200(result)


@router.post('/server/date/task/', summary="启动同步应用服务监控数据的异步任务", description="服务质量-应用服务")
async def post_qos_server_date_task(data: PostServerDateTask, db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_server_date_handler = QosServerDateHandler()
    data = {"date": data.quality_date.strftime("%Y-%m-%d")}
    result = qos_server_date_handler.post_host_date_task(db, data)
    if not result:
        message = "post server date task failed"
        logger.error(f"{message} => data:{data}")
        return resp_400(message)
    return resp_200(result)









#### 绘图接口操作 ####
@router.get('/paint/container/oversell/', summary="获取容器服务的超卖信息", description="服务质量-画布")
async def get_qos_container_server_resources_oversell(db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_paint_diagram_handler = QosPaintDiagramHandler()
    result = qos_paint_diagram_handler.get_container_server_resources_oversell(db)
    if not result:
        message = "get container server resources oversell failed"
        logger.error(message)
        return resp_400(message)
    return resp_200(result)


@router.get('/paint/server/overview/', summary="获取应用服务资源的概览信息", description="服务质量-画布")
async def get_qos_server_resources_overview(quality_date: date,
                                        classes: PaintClassesServer = Query(PaintClassesServer.class1, description="服务类型"),
                                        db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_paint_diagram_handler = QosPaintDiagramHandler()
    quality_date = quality_date.strftime("%Y-%m-%d")
    result = qos_paint_diagram_handler.get_server_resources_overview(db, quality_date, classes)
    if not result:
        message = "get server resources overview failed"
        logger.error(message)
        return resp_400(message)
    return resp_200(result)


@router.get('/paint/host/overview/', summary="获取服务器务资源的概览信息", description="服务质量-画布")
async def get_qos_host_resources_overview(quality_date: date,
                                      classes: PaintClassesHost = Query(PaintClassesHost.class1, description="机器类型"),
                                      db: Session = Depends(get_db), user=Depends(permission_checker)):
    qos_paint_diagram_handler = QosPaintDiagramHandler()
    quality_date = quality_date.strftime("%Y-%m-%d")
    result = qos_paint_diagram_handler.get_host_resources_overview(db, quality_date, classes)
    if not result:
        message = "get server resources overview failed"
        logger.error(message)
        return resp_400(message)
    return resp_200(result)


# # @router.get('/paint/host/cluster/', summary="获取服务器(cpu/mem/diskio)的监控信息, 根据集群", description="服务质量-画布")
# # async def get_qos_host_prom_by_cluster(cluster_name: PaintClusterName = Query(..., description="集群类型"),
# #                                    time_range: PaintTimeRange = Query(..., description="时间范围"),
# #                                    prom_metrics: PaintPromMetrics = Query(..., description="监控指标"),
# #                                    db: Session = Depends(get_db), user=Depends(permission_checker)):
# #     cluster_map = {
# #         "k8s-cluster": "k8s集群",
# #         "db-cluster": "数据库集群",
# #         "bigdata-offline-cluster": "大数据离线集群",
# #         "bigdata-realtime-cluster": "大数据实时集群"
# #     }
# #     cluster = cluster_map[cluster_name]
# #     qos_paint_diagram_handler = QosPaintDiagramHandler()
# #     result, data = qos_paint_diagram_handler.get_host_prom_by_cluster(db, cluster, time_range, prom_metrics)
# #     if not result:
# #         message = "get host prom by cluster failed"
# #         logger.error(message)
# #         return resp_400(message)
# #     return resp_200(data)


# @router.get('/paint/request/time/', summary="获取http平均请求时间", description="服务质量-画布")
# async def get_qos_request_time(date_month: str, db: Session = Depends(get_db), user=Depends(permission_checker)):
#     result = http_reg_time_ratio_chart_handler(date_month, db)
#     if not result:
#         message = "get server request_time overview failed"
#         logger.error(message)
#         return resp_400(message)
#     return resp_200(result)


# @router.get('/paint/request/http_4xx/', summary="获取4xx异常分布", description="服务质量-画布")
# async def get_qos_request_http_4xx(date_month: str, db: Session = Depends(get_db), user=Depends(permission_checker)):
#     result = http_4xx_chart_handler(date_month, db)
#     if not result:
#         message = "get server http_status_4xx overview failed"
#         logger.error(message)
#         return resp_400(message)
#     return resp_200(result)


# @router.get('/paint/request/http_5xx/', summary="获取5xx异常分布", description="服务质量-画布")
# async def get_qos_request_http_5xx(date_month: str, db: Session = Depends(get_db), user=Depends(permission_checker)):
#     result = http_5xx_chart_handler(date_month, db)
#     if not result:
#         message = "get server http_status_5xx overview failed"
#         logger.error(message)
#         return resp_400(message)
#     return resp_200(result)







#### 上报数据接口操作 ####
@router.post('/export/process/io/', summary="上报程序磁盘io数据", description="服务质量-程序磁盘io")
async def post_qos_export_process_io(data: ReportProcessIoList, db: Session = Depends(get_db), user=Depends(permission_checker)):
    result = data.dict().get("items", [])
    if not result:
        message = "report process io data failed"
        logger.error(message)
        return resp_400(message)
    QosProcessIo.saves(db,result)
    return resp_200()
